package com.bite.captcha.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ICaptcha;
import com.bite.captcha.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RequestMapping("/captcha")
@RestController
public class CaptchaController {
    @Autowired
    private CaptchaProperties captchaProperties;

    //校验时间设置
    private static long VALUE_TIME = 60*1000;
    //获取验证码
    @RequestMapping("/get")
    public void getCaptcha(HttpSession session,HttpServletResponse response) {
        ICaptcha captcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
        try {
            captcha.write(response.getOutputStream());
            //禁止缓存
            response.setHeader("Prama","No-cache");
            //设置返回的格式
            response.setContentType("image/jpeg");
            //打印验证码
            System.out.println(captcha.getCode());
            //存储session
            session.setAttribute(captchaProperties.getSession().getCode(),captcha.getCode());
            session.setAttribute(captchaProperties.getSession().getDate(),System.currentTimeMillis());
            //关闭getOutputStream
            response.getOutputStream().close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    //校验验证码
    @RequestMapping("/check")
    public Boolean check(String captchaCode,HttpSession session) {
        System.out.println("接收captchaCode:"+captchaCode);
        //参数校验
        if(!StringUtils.hasLength(captchaCode)) {
            return false;
        }
        String sessionCode = (String) session.getAttribute(captchaProperties.getSession().getCode());
        Long sessionDate = (Long) session.getAttribute(captchaProperties.getSession().getDate());

        //判断用户输入的验证码是否和session中的一致
        if(captchaCode.equalsIgnoreCase(sessionCode)
                &&sessionDate!=null
                &&System.currentTimeMillis()-sessionDate<VALUE_TIME)
            return true;
        return false;
        //是否在有效期内
    }
}

